package com.hobobe.tailor.aop;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import com.hobobe.tailor.common.util.ZlibUtil;

@Component 
@Aspect
public class ControllerAdvice {
	private static final Logger logger = Logger.getLogger(ControllerAdvice.class);
	
	@Before("execution(public * com.hobobe.tailor.controller.*.*(..))")
	public void beforeMethod(JoinPoint point) {
	}
	/**
	 * 过滤返回客户端结果并对结果数据进行zlib压缩
	 * @param point
	 * @return
	 * @throws Throwable
	 */
	@Around("execution(public String com.hobobe.tailor.controller.*.*(..))")
	public Object aroundMethod(ProceedingJoinPoint point) throws Throwable {
		 String result = (String)point.proceed();
		 byte[] bresult = ZlibUtil.deflate(result.getBytes());
		 if(bresult!=null){
			 return Base64.encodeBase64String(bresult);
		 }
		 return StringUtils.EMPTY;
	}
	
	
	@AfterReturning(pointcut = "execution(public String com.hobobe.tailor.controller.*.*(..))"
			,returning="result")
	public void afterReturningMethod(JoinPoint point,Object result) {
	}
	@AfterThrowing( pointcut="execution(* com.hobobe.tailor.controller.*.*(..))",throwing="ex")  
    public void afterThrowing( JoinPoint point,Throwable ex) {  
		logger.error("ControllerAdvice.doRecoverActions(..) catch "+point.getTarget().getClass()+" error,",ex);
    }  
	
}
